import { FormProvider } from '@formily/react';
import {
  ArrayCards, ArrayCollapse,
  ArrayItems, ArrayTable, Cascader, DatePicker, Editable,
  FormButtonGroup,
  FormDrawer,
  FormItem,
  FormLayout, FormTab,
  Input,
  NumberPicker, Password, Radio,
  Reset, Select,
  Submit,
} from '@formily/antd-v5';
import { ISchema, createSchemaField } from '@formily/react'
import { message, Space } from 'antd';
import PictureWall from '@/components/picturewall';
import { Form } from '@formily/core/esm/models';

const SchemaField = createSchemaField({
  components: {
    FormItem,
    Input,
    NumberPicker,
    FormTab,
    ArrayItems,
    Select,
    DatePicker,
    Space,
    ArrayCards,
    ArrayTable,
    ArrayCollapse,
    Cascader,
    PictureWall,
    Editable,
    FormLayout,
    Password,
    Radio,
  },
})

export type FormProps = {
  form: Form,
  schema: ISchema,
  saveRequest: (values: any) => any,
  detailRequest: (id: string) => any,
  emptyDetailInfo: any,
  scope?: any,
}

export const useDrawerForm = (props: FormProps) => {
  const {form, schema, saveRequest, detailRequest, emptyDetailInfo, scope} = props;
  const createFromDrawer = (title: string, schema:ISchema, handler: (values: any) => any) => {
    return FormDrawer({ title, width: '60%' }, () => {
      return (
        <FormProvider form={form}>
          <FormLayout labelCol={4} wrapperCol={20}>
            <SchemaField schema={schema} scope={{...scope}} />
            <FormDrawer.Extra>
              <FormButtonGroup align="right">
                <Submit
                  onSubmit={handler}
                >
                  提交
                </Submit>
                <Reset>重置</Reset>
              </FormButtonGroup>
            </FormDrawer.Extra>
          </FormLayout>
        </FormProvider>
      )
    });
  }

  const showForm = async (id: string|null, onClose: any) => {
    if (id && id !== '') {
      const data = await detailRequest(id);
      form.setValues(data)
      form.setInitialValues(data)
    }
    else {
      form.setValues(emptyDetailInfo)
      form.setInitialValues(emptyDetailInfo)
    }
    const drawer = createFromDrawer('编辑', schema, async (value) => {
      let resp = await saveRequest(value);
      if (resp.success) {
        message.success('操作成功');
        drawer.close();
        await onClose();
        return true;
      }
      message.error('操作失败');
      return false;
    });
    await drawer.open();
  }

  return {showForm}
}

